package com.jy.app.lib.net;

import android.util.Log;

import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.jy.app.lib.R;
import com.jy.app.lib.application.BaseApplication;
import com.jy.app.lib.bean.BaseEntity;
import com.jy.app.lib.bean.BaseResponse;
import com.jy.app.lib.utils.JsonUtil;
import com.jy.app.lib.utils.LogUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractList;
import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;


/**
 * 解析json的httpResponseHandler:
 * 对于token失效后未做处理，直接回调失败方法
 * Created by jan on 2016/4/20.
 */
public class ProwlJsonResponseHttpHandler<T> extends BaseJsonHttpResponseHandler<BaseResponse<T>> implements BaseResponseHandler<T> {

    private TypeReference<T> type = null;
    private BaseResponse<T> baseResponse;

    public ProwlJsonResponseHttpHandler(TypeReference<T> type) {
        this.type = type;
    }

    public ProwlJsonResponseHttpHandler() {
    }

    @Override
    public void onSuccess(int i, Header[] headers, String s, BaseResponse<T> type) {
        if (HttpUtil.ENABLE_LOG) {
            LogUtil.d("[HttpUtils]->response:" + s);
        }
        if (type != null) {
            if (type instanceof BaseResponse) {
                baseResponse = ((BaseResponse) type);
                if (baseResponse.getCode() != 0) {
                    try {
                        if (baseResponse.getCode() == 500) {
                            LogUtil.w("---token已经失效---");
                        }
                        onFailure(baseResponse.getCode(), baseResponse.getMsg());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
                if (baseResponse.getData() != null && !"".equals(baseResponse.getData().toString().trim())) {
                    Type type_ = ((ParameterizedType) this.type.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                    if (type_.equals(String.class)) {
                        onSuccess((T) baseResponse.getData(), baseResponse.getMsg());
                    } else if (type_.equals(Boolean.class)) {
                        onSuccess((T) Boolean.valueOf((Boolean) baseResponse.getData()), baseResponse.getMsg());
                    } else if (type_.equals(Integer.class)) {
                        onSuccess((T) Integer.valueOf((Integer) baseResponse.getData()), baseResponse.getMsg());
                    } else if (type_.equals(Double.class)) {
                        onSuccess((T) Double.valueOf((Double) baseResponse.getData()), baseResponse.getMsg());
                    } else {
                        try {
                            String jsonStr = baseResponse.getData().toString();
                            T obj = JsonUtil.parseObject(baseResponse.getData().toString(), this.type);
                            Class parentCls = obj.getClass().getSuperclass();
                            if(parentCls.equals(BaseEntity.class)){
                                ((BaseEntity)obj).androidJsonObject = jsonStr;
                            }else if(parentCls.equals(AbstractList.class)){
                                ArrayList list = (ArrayList)obj;
                                if(list.size()>0){
                                    Class itemParentCls = list.get(0).getClass().getSuperclass();
                                    if(itemParentCls.equals(BaseEntity.class)){
                                        for(Object entity:list){
                                            ((BaseEntity)entity).androidJsonObject = JsonUtil.toJson(entity);
                                        }
                                    }
                                }
                            }
                            onSuccess(obj, baseResponse.getMsg());
                        } catch (Exception e) {
                            e.printStackTrace();
                            onFailure(10000, "数据解析异常");
                        }
                    }
                } else {
                    onSuccess(null, baseResponse.getMsg());
                }
            }
        } else {
            onFailure(10000, "数据异常，请重新操作");
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, BaseResponse<T> errorResponse) {
        LogUtil.d("onFailure->statusCode=" + statusCode);
        onFailure(10000, BaseApplication.appContext.getString(R.string.your_network_not_ok));
    }

    @Override
    protected BaseResponse<T> parseResponse(String s, boolean isFail) {
        BaseResponse<T> t = null;
        try {
            if (!isFail) {
//            t = JsonUtil.parseObject(s, cls);
                t = (BaseResponse<T>) JsonUtil.parseObject(s, new TypeReference<BaseResponse<T>>() {
                });
            } else {
                //TODO 错误类型我们要定义好参数和实体，在此序列
            }
        } catch (Exception e) {
            Log.e("JsonResponseHttpHandler", "parseResponse err:", e);
            onFailure(10000, "网络数据解析异常");
        }
        return t;
    }

    @Override
    public void onSuccess(T t, String msg) {
        onSuccess(t);
    }

    @Override
    public void onSuccess(T response) {
    }

    @Override
    public void onFailure(int failCode, String failSource) {
    }

    public BaseResponse<T> getOriginalResponse() {
        return baseResponse;
    }
}
